<?php

namespace App\Admin\Controllers;

use App\Models\Customer;
use App\Models\PhoneList;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CustomerController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Customer(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('phone');
            $grid->column('notes')->editable();
            $grid->column('see','查看通讯录')->display(function (){
                return '<a href="/admin/phone_list?id=&phone=from&from='.urlencode($this->phone).'" style="color: green;">点击查看通讯录</a>';
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Customer(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('phone');
            $show->field('notes');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Customer(), function (Form $form) {
            $form->display('id');
            $form->text('name');
            $form->text('phone');
            $form->text('notes');
            $form->display('created_at');
            $form->display('updated_at');
            $form->deleted(function (Form $form){
                try {
                    $data = $form->model()->toArray();
                    foreach ($data as $index => $value){
                        PhoneList::where('from',$value['phone'])->delete();
                    }
                    return $form->response()->success('删除成功');
                } catch (\Exception $e) {
                    return $form->response()->error('数据删除失败');
                }
            });
        });
    }
}
